﻿/**************************************************************************
创建时间:	2019/5/16
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：应用MDI主窗口
记	录：
***************************************************************************/
using ASmile.Com;
using ASmile.DBModel;
using ASmile.Extend;
using ASmile.Helpers;
using ASmile.Win.Forms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace ASmile.Win
{
    public partial class FrmMDIMain : FrmMDI
    {
        public FrmMDIMain()
        {
            InitializeComponent();
        }

        #region 初始化菜单及工具栏
        /// <summary>
        /// 返回dockPanel控件
        /// </summary>
        public virtual DockPanel DockPanelControl { get; }

        protected virtual ToolStrip ToolStripControl { get; }

        protected virtual MenuStrip MenuStripControl { get; }

        protected bool IsRegisterPrintControl { set; get; } = true;

        protected virtual FrmBase CreateChangeUserForm()
        {
            throw new NotImplementedException("未实现创建登陆窗口");
        }

        protected virtual FrmBase CreateSetUserInfoForm()
        {
            throw new NotImplementedException("未实现创建设置用户信息");
        }

        //protected virtual FrmBase CreateChangePwdForm()
        //{
        //    throw new NotImplementedException("未实现修改密码窗口");
        //}

        //protected virtual FrmBase CreateVerifyPwdForm()
        //{
        //    throw new NotImplementedException("未实现修改密码窗口");
        //}

        protected virtual IMDIBLL BLLObj { get; } = ObjectFactory.GetObject<IMDIBLL>("MDIBLL");

        /// <summary>
        /// 加载更改用户及修改密码之后的系统公共（与角色权限无关）菜单
        /// </summary>
        protected virtual void SetSysMenuItem(ToolStripMenuItem menuItem)
        { }

        protected virtual void Init()
        {
            if (MenuStripControl == null) return;
            CreateMenus();
            LoadSysMenus();
        }

        void CreateMenus()
        {
            if (MenuStripControl == null) return;
            MenuStripControl.Items.Clear();
            List<Sys_RoleMenu> menus = BLLObj.GetMenuByRole();
            GC.Collect();
            if (menus == null)
            {
                MessageBox.Show("没有任何菜单权限");
                return;
            }
            var rootMenus = menus.Where(s => s.PId.IsEmpty());
            foreach (var rootMenu in rootMenus)
            {
                var tsmi = CreateToolItem(rootMenu);
                MenuStripControl.Items.Add(tsmi);
                LoadSubMenus(tsmi as ToolStripMenuItem);
            }

            ToolStripItem CreateToolItem(Sys_RoleMenu menu)
            {
                var tsmi = new ToolStripMenuItem();
                tsmi.Tag = menu;
                tsmi.Name = menu.Id;
                tsmi.Text = menu.MenuCaption;
                if (menu.IsMenu && !menu.MenuName.IsEmpty())
                {
                    tsmi.Click += MenuItemClick;
                }
                return tsmi;
            }

            void LoadSubMenus(ToolStripMenuItem pMenu)
            {
                if (pMenu == null) return;

                foreach (var menu in menus)
                {
                    if (pMenu.Name.Equals(menu.PId, StringComparison.OrdinalIgnoreCase))
                    {
                        var tsmi = CreateToolItem(menu);
                        pMenu.DropDownItems.Add(tsmi);
                        if (menu.IsMenuSplit)
                        {
                            pMenu.DropDownItems.Add(new ToolStripSeparator());
                        }
                        LoadSubMenus(tsmi as ToolStripMenuItem);
                    }
                }
            }
            InitToolBarMenus(menus);
        }

        void MenuItemClick(object sender, EventArgs e)
        {
            var tsmi = sender as ToolStripMenuItem;
            var menuObj = tsmi.Tag as Sys_RoleMenu;
            MenuClickHandle(menuObj);
        }

        void MenuClickHandle(Sys_RoleMenu menuObj)
        {
            if (menuObj.IsModalForm)
            {
                var frm = CreateForm(menuObj.MenuName);
                frm.Text = menuObj.MenuCaption;
                frm.ControlRightsArgs = menuObj.ControlRights;
                frm.MenuArgs = menuObj.MenuArgs;
                frm.MinimizeBox = false;
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.ShowDialog();
            }
            else
            {
                var frm = CreateSingletonForm(menuObj.MenuName, menuObj.Id);
                //var frm = CreateSingletonForm(
                //    menuObj.MenuArgs.IsEmpty() ? menuObj.MenuName : $"{menuObj.MenuName}-{menuObj.MenuArgs}");
                frm.Text = menuObj.MenuCaption;
                frm.ControlRightsArgs = menuObj.ControlRights;
                frm.MenuArgs = menuObj.MenuArgs;
                frm.Show(DockPanelControl);
            }
        }

        void LoadSysMenus()
        {
            //隐藏\显示 工具栏处理
            ToolStripMenuItem tsItemShow = new ToolStripMenuItem();
            tsItemShow.Text = "隐藏工具栏(&V)";
            tsItemShow.Click += (sender, e) =>
            {
                ToolStripControl.Visible = !ToolStripControl.Visible;
                if (ToolStripControl.Visible)
                {
                    tsItemShow.Text = "隐藏工具栏(&V)";
                }
                else
                {
                    tsItemShow.Text = "显示工具栏(&V)";
                }
            };
            MenuStripControl.Items.Add(tsItemShow);

            ToolStripMenuItem sys = new ToolStripMenuItem();
            sys.Text = "帮助(&H)";
            ToolStripMenuItem changeUser = new ToolStripMenuItem();
            changeUser.Text = "切换用户";
            changeUser.Click += (sender, e) =>
            {
                var frm = CreateChangeUserForm();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    //如果不是用原操作解锁
                    IDockContent[] documents = DockPanelControl.DocumentsToArray();
                    foreach (IDockContent content in documents)
                    {
                        content.DockHandler.Close();
                    }
                    Init();
                }
            };
            sys.DropDownItems.Add(changeUser);

            ToolStripMenuItem setUserInfo = new ToolStripMenuItem();
            setUserInfo.Text = "修改用户信息";
            setUserInfo.Click += (sender, e) =>
            {
                var frm = CreateSetUserInfoForm();
                frm.ShowDialog();
            };
            sys.DropDownItems.Add(setUserInfo);


            ToolStripMenuItem changePwd = new ToolStripMenuItem();
            changePwd.Text = "修改密码";
            changePwd.Click += (sender, e) =>
            {
                var frm = new FrmChangePwd(); // CreateChangePwdForm();
                frm.ShowDialog();
            };
            sys.DropDownItems.Add(changePwd);
            //注册打印组件
            if (IsRegisterPrintControl)
            {
                ToolStripMenuItem registerPrint = new ToolStripMenuItem();
                registerPrint.Text = "注册打印组件";
                registerPrint.Click += RegisterPrintControl;
                sys.DropDownItems.Add(registerPrint);
            }

            ToolStripMenuItem abort = new ToolStripMenuItem("关于");
            abort.Click += (sender, e) =>
            {
                var frm = new FrmAbort();
                frm.ShowDialog();
            };
            sys.DropDownItems.Add(abort);

            ToolStripMenuItem tsmiExit = new ToolStripMenuItem();
            tsmiExit.Text = "退出";
            tsmiExit.Click += (sender, e) =>
            {
                this.Close();
            };
            SetSysMenuItem(sys);

            sys.DropDownItems.Add(tsmiExit);
            MenuStripControl.Items.Add(sys);

            ToolStripButton tsbtn = CreateToolBarButton("锁定", ASmile.Win.Properties.Resources._lock);
            tsbtn.Click += LockFormHandle;
            ToolStripControl.Items.Add(tsbtn);
        }

        protected virtual void RegisterPrintControl(object sender, EventArgs e)
        {
            try
            {
                string targetDir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                if (Environment.Is64BitOperatingSystem)
                {
                    Process.Start($"Regsvr32.exe", $"{targetDir}PrintCOM\\x64\\grdes6x64.dll");
                    Process.Start($"Regsvr32.exe", $"{targetDir}PrintCOM\\x64\\gregn6x64.dll");
                }
                else
                {
                    Process.Start($"Regsvr32.exe", $"{targetDir}PrintCOM\\x86\\grdes6.dll");
                    Process.Start($"Regsvr32.exe", $"{targetDir}PrintCOM\\x86\\gregn6.dll");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LogHelper.LogObj.Error("注册COM组件发生异常", ex);
            }
        }

        void MenuToolBarClick(object sender, EventArgs e)
        {
            var tsbtn = sender as ToolStripButton;
            var menuObj = tsbtn.Tag as Sys_RoleMenu;
            MenuClickHandle(menuObj);
        }

        void InitToolBarMenus(IEnumerable<Sys_RoleMenu> menus)
        {
            ToolStripControl.Items.Clear();
            var toolMenus = menus.Where(s => s.ToolBarVisible && s.IsMenu == true).OrderBy(s => s.ToolBarOrderNo);
            if (toolMenus != null)
            {
                foreach (var menu in toolMenus)
                {
                    ToolStripButton tsb = CreateToolBarButton(menu.ToolBarCaption);
                    tsb.Text = menu.ToolBarCaption;
                    tsb.Tag = menu;
                    if (!menu.ToolBarIcon.IsEmpty())
                    {
                        var iconFile = Path.Combine(Application.StartupPath, Config.Settings.IconFolder, menu.ToolBarIcon);
                        if (File.Exists(iconFile))
                        {
                            var img = Image.FromFile(iconFile);
                            tsb.Image = ImageHelper.SmallBitByCanva(img, 32, 32);
                        }
                    }
                    tsb.Click -= MenuToolBarClick;
                    tsb.Click += MenuToolBarClick;

                    ToolStripControl.Items.Add(tsb);
                    if (menu.ToolBarSplit)
                    {
                        ToolStripSeparator tss = new ToolStripSeparator();
                        ToolStripControl.Items.Add(tss);
                    }
                }
            }
        }

        ToolStripButton CreateToolBarButton(string text, Image img = null)
        {
            ToolStripButton tsbtn = new ToolStripButton();
            tsbtn.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
            if (img != null)
            {
                tsbtn.Image = img;
            }
            tsbtn.ImageScaling = ToolStripItemImageScaling.None;
            tsbtn.ImageTransparentColor = Color.Magenta;
            //tsbtn.Name = "tsBtnLock";
            tsbtn.Size = new Size(73, 35);
            tsbtn.Text = text;
            return tsbtn;
        }

        private void LockFormHandle(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            //隐藏任务栏区图标 
            this.ShowInTaskbar = false;
            //图标显示在托盘区 
            notifyIcon.Visible = true;
        }

        #endregion

        private void FrmMDIMain_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                Init();
                notifyIcon.Icon = this.Icon;
                notifyIcon.Text = this.Text;
                notifyIcon.DoubleClick += NotifyIconControl_DoubleClick;
            }

        }

        private void NotifyIconControl_DoubleClick(object sender, EventArgs e)
        {
            if (this.ShowInTaskbar == false && notifyIcon.Visible == true)
            {
                var verifyForm = new FrmVerifyPwd();
                verifyForm.StartPosition = FormStartPosition.CenterScreen;
                verifyForm.TopMost = true;

                ThreadPool.QueueUserWorkItem((state) =>
                {
                    Thread.Sleep(50);
                    verifyForm.Activate();
                });

                if (verifyForm.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                var ret = BLLObj.VerifyPwd(verifyForm.Pwd);
                if (!ret)
                {
                    MessageBox.Show(ret.msg);
                    return;
                }
                //还原窗体显示 
                this.WindowState = FormWindowState.Maximized;
                //激活窗体并给予它焦点 
                this.Activate();
                //任务栏区显示图标 
                this.ShowInTaskbar = true;
                //托盘区图标隐藏 
                notifyIcon.Visible = false;
                //打开一个窗口再关闭,当最小化托盘后再打开,dockpanel的子窗口会显示不正常
                var frm = CreateSingletonForm<FrmBase>();
                frm.Show(this.DockPanelControl);
                frm.Close();

            }
        }

        private void FrmMDIMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ShowQuestion("确实要退出系统吗?", "退出确认"))
            {
                e.Cancel = true;
            }
            try
            {
                BLLObj?.LoginOut();
            }
            catch (Exception ex)
            {
                LogHelper.LogObj.Error("退出调用Http异常", ex);
            }            
        }
    }
}